package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器类
 *
 * @author hua
 * @since 2022/11/1 16:39
 */
//annotations指定拦截范围
//@RestControllerAdvice=@ControllerAdvice+@ResponseBody
@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//指定捕获异常的类型
    public R<String> ExceptionHandler(SQLIntegrityConstraintViolationException ex){
     log.error(ex.getMessage());
     //Duplicate entry 'admin' for key 'idx_username'
     //重复数据问题 //判断是否包含Duplicate entry字符串
        //getMessage()获取异常信息
     if (ex.getMessage().contains("Duplicate entry")){
         String[] split = ex.getMessage().split(" ");
         //重复的数据
         String duplicateKey= split[2];
         return R.error(duplicateKey+ "=== 数据已存在");
     }
     return R.error("未知错误");
    }
    @ExceptionHandler(CustomException.class)//指定捕获异常的类型
    public R<String> ExceptionHandler(CustomException ex){
      log.info(ex.getMessage());
      return R.error(ex.getMessage());
    }
}
